import { useState, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import './index.scss'

const RangeSlider = ({
    min = 0,
    max = 100,
    step = 1,
    defaultValue = [],
    disabled = false,
    onChange
}) => {
    const [values, setValues] = useState([0, 0]);
    const [dragging, setDragging] = useState(null);
    const containerRef = useRef(null);
    const [dimensions, setDimensions] = useState({ width: 0, left: 0 });

    // 初始化或重置值
    const resetValues = () => {
        setValues(defaultValue);
        if (onChange) onChange(defaultValue);
    };
    useEffect(() => {
        setValues(defaultValue)
    }, [defaultValue])
    // 获取容器尺寸
    useEffect(() => {
        const getDimensions = () => {
            const query = Taro.createSelectorQuery();
            query.select('.slider-container').boundingClientRect(rect => {
                if (rect) {
                    setDimensions({
                        width: rect.width,
                        left: rect.left
                    });
                }
            }).exec();
        };

        getDimensions();
        // 监听窗口变化
        const resizeHandler = () => {
            getDimensions();
        };

        Taro.eventCenter.on('windowResize', resizeHandler);
        return () => {
            Taro.eventCenter.off('windowResize', resizeHandler);
        };
    }, []);

    // 处理滑块拖动开始
    const handleTouchStart = (type) => {
        if (disabled) return;
        setDragging(type);
        Taro.vibrateShort(); // 轻微震动反馈
    };

    // 处理滑块拖动
    const handleTouchMove = (e) => {
        if (disabled || dragging === null || dimensions.width === 0) return;

        const touch = e.touches[0];
        const position = Math.min(Math.max(touch.pageX - dimensions.left, 0), dimensions.width);
        const percentage = position / dimensions.width;
        const newValue = Math.round(min + percentage * (max - min));

        // 确保值在范围内且符合步长
        const adjustedValue = Math.round(newValue / step) * step;

        // 更新对应滑块的值
        setValues(prev => {
            let newMin = prev[0];
            let newMax = prev[1];

            if (dragging === 'min') {
                newMin = Math.min(Math.max(adjustedValue, min), newMax - step);
            } else {
                newMax = Math.max(Math.min(adjustedValue, max), newMin + step);
            }

            const newValues = [newMin, newMax];
            if (onChange) onChange(newValues);
            return newValues;
        });
    };

    // 结束拖动
    const handleTouchEnd = () => {
        setDragging(null);
    };

    // 计算滑块位置（百分比）
    const minPosition = ((values[0] - min) / (max - min)) * 100;
    const maxPosition = ((values[1] - min) / (max - min)) * 100;
    console.log(values)
    return (
        <View className={`range-slider-container ${disabled ? 'disabled' : ''}`}>
            <View
                className="slider-container"
                ref={containerRef}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
                onTouchCancel={handleTouchEnd}
            >
                <View className="slider-track" />
                <View
                    className="slider-range"
                    style={{
                        left: `${minPosition}%`,
                        width: `${maxPosition - minPosition}%`
                    }}
                />
                {/* 最小值滑块 */}
                <View
                    className={`slider-thumb min-thumb ${dragging === 'min' ? 'active' : ''}`}
                    style={{ left: `${minPosition}%` }}
                    onTouchStart={() => handleTouchStart('min')}
                >
                    {values[0]}
                </View>

                {/* 最大值滑块 */}
                <View
                    className={`slider-thumb max-thumb ${dragging === 'max' ? 'active' : ''}`}
                    style={{ left: `${maxPosition}%` }}
                    onTouchStart={() => handleTouchStart('max')}
                >
                    {values[1]}
                </View>
            </View>
        </View>
    );
};

export default RangeSlider;